package com.bls.cate.ui.activity.root;

import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bls.blslib.base.BaseActivity;
import com.bls.blslib.eventbus.Event;
import com.bls.cate.R;
import com.bls.cate.constant.EventBusCode;
import com.bls.cate.constant.Interface;
import com.bls.cate.model.LoginRes;
import com.bls.cate.model.LoginSpRes;
import com.bls.cate.ui.activity.attention.AttentionActivity;
import com.bls.cate.ui.activity.login.LoginActivity;
import com.bls.cate.ui.activity.person.PersonActivity;
import com.bls.cate.ui.activity.publish_manage.PublishManageActivity;
import com.bls.cate.ui.activity.search_user.SearchUserActivity;
import com.bls.cate.ui.activity.setting.SettingActivity;
import com.bls.cate.ui.fragment.User.UserFragment;
import com.bls.cate.ui.fragment.article.ArticleFragment;
import com.bls.cate.utils.AccountUtil;
import com.bls.cate.utils.FrescoImageLoader;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;

/**
 * 　　  () 　　　  ()
 * 　　  ( ) 　　　( )
 * 　　  ( ) 　　　( )
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　┻　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ——————————————————
 * Created by BinglingSu on 2018/1/2.
 */
public class RootActivity extends BaseActivity {

    private DrawerLayout dlRoot;
    private ScrollView svLeft;
    private SimpleDraweeView btnHeader, btnLeftHeader;
    private RelativeLayout btnClass1, btnClass2;
    private TextView tvLeftName, btnTvLover, btnTvAttention, btnTvMyPublish, btnTvSetting, btnTvMsg, btnTvChat;
    private RelativeLayout btnLover, btnAttention, btnMyPublish, btnMsg, btnSetting, btnChat;
    private ImageView ivClass1, ivClass2, ivMsgUnRead, ivChatUnRead;

    private static int SCREEN_WIDTH = ScreenUtils.getScreenWidth();

    private static RootActivity mActivity = null;
    private ArrayList<Fragment> fragments;
    private Fragment hideFrag = null; //将要隐藏的Fragment
    private long lastBackTime;
    private int mobIMUnReadCount = 0;   //MobIM 未读消息数量

    public static RootActivity getInstance() {
        if (null != mActivity)
            return mActivity;
        else return null;
    }

    @Override
    protected void initParams() {
        super.initParams();
        mActivity = (RootActivity) getActivity();
        UserFragment userFragment = UserFragment.newInstance("", "");
        ArticleFragment articleFragment = ArticleFragment.newInstance("", "");
        fragments = new ArrayList<>();
        fragments.add(userFragment);
        fragments.add(articleFragment);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_root;
    }

    @Override
    protected void initFvb() {
        dlRoot = findViewById(R.id.dl_root);
        svLeft = findViewById(R.id.sv_left);
        dlRoot.setScrimColor(Color.TRANSPARENT);
        btnHeader = findViewById(R.id.btn_header);
        btnClass1 = findViewById(R.id.btn_class_1);
        btnClass2 = findViewById(R.id.btn_class_2);
        ivClass1 = findViewById(R.id.iv_class_1);
        ivClass2 = findViewById(R.id.iv_class_2);
        btnLeftHeader = findViewById(R.id.iv_left_header);
        tvLeftName = findViewById(R.id.tv_left_name);
        btnTvLover = findViewById(R.id.btn_tv_lover);
        btnTvSetting = findViewById(R.id.btn_tv_setting);
        btnTvAttention = findViewById(R.id.btn_tv_attention);
        btnTvMyPublish = findViewById(R.id.btn_tv_my_publish);
        btnTvMsg = findViewById(R.id.btn_tv_msg);
        btnTvChat = findViewById(R.id.btn_tv_chat);
        btnLover = findViewById(R.id.btn_lover);
        btnAttention = findViewById(R.id.btn_attention);
        btnMyPublish = findViewById(R.id.btn_my_publish);
        btnMsg = findViewById(R.id.btn_msg);
        btnChat = findViewById(R.id.btn_chat);
        btnSetting = findViewById(R.id.btn_setting);
        ivMsgUnRead = findViewById(R.id.iv_msg_unread);
        ivChatUnRead = findViewById(R.id.iv_chat_unread);
    }

    @Override
    protected void initView() {
        initLeft();
        switchFrag(0);
    }

    @Override
    protected void initListener() {
        setOnClickListener(btnHeader, btnClass1, btnClass2, btnLeftHeader, btnLover, btnAttention, btnMyPublish, btnMsg, btnSetting, btnChat);
    }

    @Override
    protected void initData() {
        if (AccountUtil.isLogin()) {
            presenter.requestStrData(Interface.INTERFACE_CODE_GET_USERINFO, Interface.INTERFACE_ACCOUNT, CacheMode.NO_CACHE, new HttpParams("RequestMethod", "GetUserInfo"), new HttpParams("UniqueId", AccountUtil.getUniqueId()));
        }
    }

    /**
     * 设置用户信息
     */
    private void setUserInfo() {
        if (AccountUtil.isLogin()) {
            LoginSpRes loginSpRes = AccountUtil.getStrLoginSp();
            FrescoImageLoader.showImage(btnHeader, loginSpRes != null ? loginSpRes.getHeaderImgSmall() : null);
            FrescoImageLoader.showImage(btnLeftHeader, loginSpRes != null ? loginSpRes.getHeaderImgMiddle() : null);
            tvLeftName.setText(loginSpRes != null ? loginSpRes.getNickName() : null);
        }
    }

    /**
     * 初始化侧栏
     */
    private void initLeft() {
        LinearLayout llLeft = findViewById(R.id.ll_left);
        FrameLayout.LayoutParams llLeftParams = (FrameLayout.LayoutParams) llLeft.getLayoutParams();
        llLeftParams.width = (int) (SCREEN_WIDTH * 0.6);
        llLeft.setLayoutParams(llLeftParams);
        Resources resources = mActivity.getResources();

        TextView[] btns = new TextView[]{btnTvAttention, btnTvMyPublish, btnTvChat, btnTvMsg, btnTvSetting};
        Drawable[] icons = new Drawable[]{
                resources.getDrawable(R.mipmap.icon_friend),
                resources.getDrawable(R.mipmap.icon_edit),
                resources.getDrawable(R.mipmap.icon_chat2),
                resources.getDrawable(R.mipmap.icon_chat),
                resources.getDrawable(R.mipmap.icon_setting)};
        String[] btnTexts = new String[]{"我的关注", "我的发布", "会话", "消息", "设置"};
        for (int i = 0, j = btns.length; i < j; i++) {
            icons[i].setBounds(0, 0, 40, 40);
            btns[i].setCompoundDrawables(icons[i], null, null, null);
            btns[i].setCompoundDrawablePadding(20);
            btns[i].setText(btnTexts[i]);
        }
    }

    /**
     * 切换Fragment
     *
     * @param index 位置
     */
    private void switchFrag(int index) {
        ivClass1.setVisibility(index == 0 ? View.VISIBLE : View.INVISIBLE);
        ivClass2.setVisibility(index == 1 ? View.VISIBLE : View.INVISIBLE);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (index == 0 && !fragments.get(0).isAdded())
            transaction.add(R.id.fl_content, fragments.get(0));
        if (index == 1 && !fragments.get(1).isAdded())
            transaction.add(R.id.fl_content, fragments.get(1));
        hideFragment(transaction, hideFrag);
        transaction.show(fragments.get(index));
        hideFrag = fragments.get(index);
        transaction.commit();
    }

    private void hideFragment(FragmentTransaction transaction, Fragment hideFrag) {
        if (null != hideFrag)
            transaction.hide(hideFrag);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_header:
                dlRoot.openDrawer(svLeft);
                break;
            case R.id.btn_class_1:
                switchFrag(0);
                break;
            case R.id.btn_class_2:
                switchFrag(1);
                break;
            case R.id.iv_left_header:
                ActivityUtils.startActivity(AccountUtil.isLogin() ? PersonActivity.class : LoginActivity.class);
                break;
            case R.id.btn_lover:
                ActivityUtils.startActivity(AccountUtil.isLogin() ? SearchUserActivity.class : LoginActivity.class);
                break;
            case R.id.btn_attention:
                ActivityUtils.startActivity(AccountUtil.isLogin() ? AttentionActivity.class : LoginActivity.class);
                break;
            case R.id.btn_my_publish:
                ActivityUtils.startActivity(AccountUtil.isLogin() ? PublishManageActivity.class : LoginActivity.class);
                break;
            case R.id.btn_chat:
                break;
            case R.id.btn_msg:
                break;
            case R.id.btn_setting:
                ActivityUtils.startActivity(SettingActivity.class);
                break;
        }
    }

    @Override
    public void showOnSuccess(int requestId, String responseBody, Response response) {
        if (requestId == Interface.INTERFACE_CODE_GET_USERINFO) {
            LoginRes loginRes = gson.fromJson(responseBody, LoginRes.class);
            if (loginRes.isResultStatus()) {
                LoginRes.ResultDataBean resultDataBean = loginRes.getResultData();
                AccountUtil.writeLoginSp(resultDataBean);
                FrescoImageLoader.showImage(btnHeader, resultDataBean.getHeaderImgSmall());
                FrescoImageLoader.showImage(btnLeftHeader, resultDataBean.getHeaderImgMiddle());
                tvLeftName.setText(resultDataBean.getNickName());
            }
        }
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveStickyEvent(Event event) {
        super.receiveStickyEvent(event);
        if (event.getCode() == EventBusCode.LOGIN_SUCCESS_REFRESH_DATE || event.getCode() == EventBusCode.ChangeUserInfo_Refresh) {
            setUserInfo();
        }
    }

    @Override
    protected void initResume() {
        super.initResume();
        setChatDot();
    }

    /**
     * 设置侧边栏会话小圆点
     */
    public void setChatDot() {

    }

    @Override
    public void onBackPressed() {
        long curTime = System.currentTimeMillis();
        if (curTime - lastBackTime < 2000) {
            super.onBackPressed();
        } else {
            lastBackTime = curTime;
            ToastUtils.showShort("再按一下后退键退出");
        }
    }

    @Override
    protected void initOnDestroy() {
        super.initOnDestroy();
    }
}
